package com.example.base.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.base.R;
import com.example.base.bean.SerachBean;
import com.example.base.view.SysViewLayout;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SerachHistoryAdapter extends BaseAdapter {
  private List<SerachBean> dataList = new ArrayList<SerachBean>();
  private Context context;

  public SerachHistoryAdapter(Context context, List<SerachBean> serachBeans) {
    this.dataList.addAll(serachBeans);
    this.context = context;
  }


  @Override
  public int getCount() {
    return dataList.size();
  }

  @Override
  public java.lang.Object getItem(int position) {
    return null;
  }

  @Override
  public long getItemId(int position) {
    return position;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    MyViewHolder myViewHolder;
    if (convertView == null) {
      myViewHolder = new MyViewHolder();
      LayoutInflater inflater = LayoutInflater.from(context);
      convertView = inflater.inflate(R.layout.list_view_sys, null, true);
      myViewHolder.flowLayout = convertView.findViewById(R.id.ViewLayout);
      convertView.setTag(myViewHolder);
    } else {
      myViewHolder = (MyViewHolder) convertView.getTag();
    }
    initFlow(Collections.singletonList(dataList.get(position)), myViewHolder.flowLayout);
    return convertView;
  }

  private void initFlow(List<SerachBean> data, SysViewLayout sysViewLayout) {
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(10, 5, 10, 5);
    if (sysViewLayout != null) {
      sysViewLayout.removeAllViews();
    }
    for (int i = 0; i < data.size(); i++) {
      TextView tv = new TextView(context);
      tv.setPadding(28, 10, 28, 10);
      tv.setText(data.get(i).getText());
      tv.setMaxEms(10);
      tv.setSingleLine();
      tv.setBackgroundResource(R.drawable.shape_textback);
      tv.setLayoutParams(layoutParams);
      sysViewLayout.addView(tv, layoutParams);
    }
  }

  public void setData(List<SerachBean> serachBeans) {
    dataList.clear();
    dataList.addAll(serachBeans);
  }

  class MyViewHolder {
    SysViewLayout flowLayout;
  }
}
